<script setup lang="ts">
import { ref, nextTick, computed, useAttrs } from 'vue'
import { components, type IForm } from './index'
import { t } from '@/lang'

const emit = defineEmits(['change'])
const props = defineProps({
    is: {
        type: String,
        default: ''
    },
    asyncClose: {
        type: Boolean,
        default: false
    },
    showCancel: {
        type: Boolean,
        default: true
    },
    showFooter: {
        type: Boolean,
        default: false
    }
})
/** 显示/隐藏 */
const visible = ref<boolean>()
const attrs = useAttrs()
const title = ref('')
const formRef = ref<IForm>()

/**
   * @description 弹框属性
   */
const drawerAttrs = computed(() => {
    return {
        size: '50%',
        showClose: true,
        title: title.value,
        appendToBody: true,
        ...attrs
    }
})

const currentComponent = computed(() => {
    if (props.is) {
        return components[props.is]
    } else {
        return null
    }
})

/**
   * @description 显示弹框
   */
function show (t: string, ...args: any[]) {
    visible.value = true
    title.value = t
    nextTick(() => {
        formRef.value?.init(...args)
        if (props.is === 'UserDetail') {
          formRef.value?.getTravelList(args[0]?.id)
        }
    })
}

function close () {
    visible.value = false
}

/**
   * @description 关闭弹框
   */
function handleCancel () {
    visible.value = false
}

/**
   * @description 保存
   */
function handleSave () {
    formRef.value?.submit().then((res: any) => {
        !props.asyncClose && (visible.value = false)
        emit('change', res)
    })
}

defineExpose({
    show,
    close
})
</script>

<template>
  <el-drawer
    draggable
    class="f-drawer"
    v-model="visible"
    v-bind="drawerAttrs"
  >
    <template #header>
      <div class="drawer-title">{{ title }}</div>
    </template>
    <el-scrollbar height="100%">
      <div class="el-drawer__main">
        <component v-if="currentComponent" ref="formRef" :is="currentComponent" />
        <span v-else>请设置组件的is属性</span>
      </div>
    </el-scrollbar>
    <template v-if="showFooter" #footer>
      <span class="drawer-footer">
        <el-button v-if="showCancel" @click="handleCancel">{{ t('form.cancel') }}</el-button>
        <el-button type="primary" @click="handleSave">{{ t('form.confirm') }}</el-button>
      </span>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">

</style>

<style lang="scss">
.el-drawer__header {
  margin-bottom: 0;
}
.el-drawer__body {
  padding: 0;
}
.el-drawer__main {
  padding: var(--el-drawer-padding-primary);
}
.f-form {
  .el-input {
    width: 400px;
  }
}
</style>
